using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.SalesManage;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using System.Linq;
using RBAC.Domain.MaterialManage;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 根据ID获取销售订单详情处理器
    /// </summary>
    public class SalesOrderGetDetailByIdHandler : IRequestHandler<SalesOrderGetDetailByIdCommand, APIResult<SalesOrderDetailDto>>
    {
        private readonly IBaseRepository<SalesOrder> salesOrderRepository;
        private readonly IBaseRepository<SalesOrderDetail> salesOrderDetailRepository;
        private readonly IBaseRepository<Mater> materRepository;
        private readonly ILogger<SalesOrderGetDetailByIdHandler> logger;
        private readonly IMapper mapper;

        public SalesOrderGetDetailByIdHandler(
            IBaseRepository<SalesOrder> salesOrderRepository,
            IBaseRepository<SalesOrderDetail> salesOrderDetailRepository,
            IBaseRepository<Mater> materRepository,
            ILogger<SalesOrderGetDetailByIdHandler> logger,
            IMapper mapper)
        {
            this.salesOrderRepository = salesOrderRepository;
            this.salesOrderDetailRepository = salesOrderDetailRepository;
            this.materRepository = materRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理根据ID获取销售订单详情请求
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>销售订单详情结果</returns>
        public Task<APIResult<SalesOrderDetailDto>> Handle(SalesOrderGetDetailByIdCommand request, CancellationToken cancellationToken)
        {
            APIResult<SalesOrderDetailDto> result = new APIResult<SalesOrderDetailDto>();

            try
            {
                logger.LogInformation("开始查询销售订单详情，订单ID：{OrderId}", request.Id);

                // 1. 查询销售订单主信息
                var salesOrder = salesOrderRepository.GetModel(request.Id);
                if (salesOrder == null)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "销售订单不存在";
                    logger.LogWarning("销售订单不存在，ID：{OrderId}", request.Id);
                    return Task.FromResult(result);
                }

                // 2. 查询销售订单明细
                var details = salesOrderDetailRepository.GetAll("SalesOrderId = @SalesOrderId", new { SalesOrderId = request.Id });

                // 3. 查询相关物料信息并构建明细DTO
                var detailDtos = new List<SalesOrderDetailItemDto>();
                var materIds = details.Select(d => d.MaterId).Distinct().ToList();

                if (materIds.Any())
                {
                    // 构建IN查询的SQL和参数
                    var inClause = string.Join(",", materIds.Select((_, index) => $"@Id{index}"));
                    var parameters = materIds.Select((id, index) => new { Key = $"@Id{index}", Value = id })
                        .ToDictionary(x => x.Key, x => (object)x.Value);

                    var maters = materRepository.GetAll($"Id IN ({inClause})", parameters);
                    var materDict = maters.ToDictionary(m => m.Id);

                    for (int i = 0; i < details.Count; i++)
                    {
                        var detail = details[i];
                        var mater = materDict.GetValueOrDefault(detail.MaterId);

                        var detailDto = new SalesOrderDetailItemDto
                        {
                            Id = detail.Id,
                            SerialNo = i + 1,
                            MaterId = detail.MaterId,
                            MaterCode = mater?.MaterCode,
                            MaterName = mater?.MaterName,
                            ModelSpec = mater?.ModelSpec,
                            Unit = mater?.Unit,
                            Num = detail.Num,
                            Price = detail.Price,
                            Amount = detail.Num.HasValue && detail.Price.HasValue ? detail.Num.Value * detail.Price.Value : 0,
                            Remark = detail.Remark,
                            CreateTime = detail.CreateTime,
                            CreateUser = detail.CreateUser
                        };

                        detailDtos.Add(detailDto);
                    }
                }

                // 4. 构建返回结果
                var salesOrderDetailDto = new SalesOrderDetailDto
                {
                    SalesOrder = mapper.Map<SalesOrderDto>(salesOrder),
                    Details = detailDtos
                };

                result.Code = APIEnums.Success;
                result.Data = salesOrderDetailDto;
                result.Msg = "获取销售订单详情成功";

                logger.LogInformation("销售订单详情查询成功，订单ID：{OrderId}，明细数量：{DetailCount}",
                    request.Id, detailDtos.Count);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询销售订单详情失败，订单ID：{OrderId}，错误信息：{Message}",
                    request.Id, ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取销售订单详情失败";
                result.Data = null;
            }

            return Task.FromResult(result);
        }
    }
}
